package com.hn658.base.message.eventbus.handler.singlechat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hn658.base.message.common.dto.NotificationDTO;
import com.hn658.base.message.common.enums.EventType;
import com.hn658.base.message.common.enums.NotifySenderType;
import com.hn658.base.message.common.enums.NotifyType;
import com.hn658.base.message.eventbus.event.singlechat.SingleMsgEvent;
import com.hn658.base.message.eventbus.handler.AbstractEventHandler;
import com.hn658.base.message.eventbus.util.NotifiConvert;
import com.hn658.base.message.notification.msg.entity.MessageEO;
import com.hn658.base.message.notification.notify.business.INotificationManager;
import com.hn658.base.message.notification.notify.entity.NotificationEO;

/**
 * Created by baihai on 2015/11/19.
 */
@Component
public class SingleMesageHandler extends AbstractEventHandler<SingleMsgEvent> {

    @Autowired
    private INotificationManager notificationManager;



    @Override
    public void handle(SingleMsgEvent event) {
		MessageEO msg = event.getMessage();
        NotificationEO notificationEO = NotifiConvert.convert(msg,event.getEventId());
        NotificationEO notifyDb = notificationManager.find(msg.getNotifyId());
        //保存或更新通知
        if(notifyDb == null){
            notificationManager.save(notificationEO);
        }else{
            notificationManager.update(notificationEO);
        }
        //判断是否正在聊天
        boolean isTalking = notificationManager.currentTalk(msg.getAppId(), msg.getFromUid(), msg.getToUid(), NotifyType.SingleChat);
        NotificationDTO notificationDTO = NotifiConvert.convert(msg,notificationEO);
        notificationDTO.setSenderType(NotifySenderType.Comet.getValue());
        int unReadCount = notificationManager.getUnReadCountByNotiId(msg.getAppId(), msg.getFromUid(), msg.getNotifyId());
        if(isTalking){
        	//是当前聊天，未读数为0,
        	notificationDTO.setUnReadCount(0);
        }else{
        	//不是当前聊天，更新设置未读数
        	unReadCount++;
        	notificationDTO.setUnReadCount(unReadCount);
        	notificationManager.saveUnReadCountByNotiId(msg.getAppId(), msg.getToUid(), msg.getNotifyId(), unReadCount);
        }
        notificationManager.send(notificationDTO);

    }

    @Override
    public EventType getTarget() {
        return EventType.NormalSingleChat;
    }
}
